package com.ysy.lock;

import java.util.concurrent.TimeUnit;

/**
 * @program: zookeeper-demo
 * @description: 测试
 * @author: yeshiyuan
 * @create: 2019-06-13 20:12
 **/
public class ZkTest {

    public static void main(String[] args) {
        //第一个线程占用锁
        Runnable task = new Runnable() {
            public void run() {
                DistributedLock lock = null;
                try {
                    lock = new DistributedLock("192.168.5.35:2181", "yeshiyuan");
                    lock.lock();
                    TimeUnit.SECONDS.sleep(3L);
                    System.out.println("===Thread " + Thread.currentThread().getId() + " running");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    if(lock != null)
                        lock.unlock();
                }
            }
        };
        new Thread(task).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        //这些线程抢锁
        ConcurrentTest.ConcurrentTask[] tasks = new ConcurrentTest.ConcurrentTask[10];
        for (int i = 0; i < tasks.length; i++) {
            ConcurrentTest.ConcurrentTask concurrentTask = new ConcurrentTest.ConcurrentTask() {
                public void run() {
                    DistributedLock lock = null;
                    try {
                        lock = new DistributedLock("192.168.5.35:2181","yeshiyuan");
                        lock.lock();
                        System.out.println("Thread " + Thread.currentThread().getId() + " running");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        lock.unlock();
                    }
                }
            };
            tasks[i] = concurrentTask;
        }
        ConcurrentTest test = new ConcurrentTest(tasks);
        test.start();
    }
}
